import React, { Component } from "react";
import {
  Divider,
  Modal,
  Tree,
  message,
  Upload,
  Button,
  Icon,
  Spin,
} from "antd";
import { connect } from "dva";
import styles from "./index.less";
// import TopSearch from "./components/TopSearch";
import Top from "./components/Top";
import TableList from "./components/TableList";
import api from "../../../services/publicApi";
// import AddUser from "./components/AddUser";

const { TreeNode, DirectoryTree } = Tree;

@connect((stores) => ({
  coldata: stores.user,
  adddataSource: stores.adddataSource,
  channelNumberData: stores.channelNumberModel,
}))
class ChannelNumber extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      pageNum: 1,
      pageSize: 10,
      totalCount: 0,
      orgCode: "",
      name: "",
      policeId: "",
      tableData: [],
      loading: false,
      spinLoading: false,
      expandedKeys: [],
    };
  }

  componentDidMount() {
    // const { coldata } = this.props;
    // const { userInfo } = coldata;
    // this.setState(
    //   {
    //     orgCode: userInfo.department || "320000000000"
    //   },
    //   () => {
    //     this.getTableData();
    //   }
    // );
    this.getTableData();
    this.getOrgList();
  }

  getTableData = () => {
    const { pageNum, pageSize, name, policeId, orgCode } = this.state;
    const { dispatch } = this.props;
    const payload = {
      pageNum,
      pageSize,
      name,
      policeId,
      orgCode,
    };
    this.setState({
      loading: true,
    });
    dispatch({ type: "channelNumber/channelList", payload }).then((res) => {
      this.setState({
        tableData: res.datas,
        totalCount: res.totalCount,
        loading: false,
      });
    });
  };

  getOrgList = async () => {
    const expandedKeys = [];
    const { dispatch } = this.props;
    const arr = await dispatch({ type: "adddataSource/getOrgList" });
    function loop(dataArr) {
      dataArr.forEach((element) => {
        if (element.children && element.children.length > 0) {
          expandedKeys.push(element.key);
          loop(element.children);
        }
      });
    }
    loop(arr);
    this.setState({
      expandedKeys,
    });
  };

  handleAdd = (visible) => {
    this.setState({
      visible,
    });
  };

  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  idaasDataSync = async () => {
    const { errCode } = await api.idaasSyncData();
    if (errCode === 0) {
      message.info("4A数据同步成功");
      // this.getTableData();
      window.location.reload();
    } else {
      message.error("4A数据同步失败");
    }
  };

  closeModal = () => {
    this.setState({
      visible: false,
    });
  };

  handleRecord = () => {};

  // 查询单条数据
  // handleRecord = record => {
  //   console.log("record", record);
  // };

  // 删除
  handleDel = (record) => {
    const { dispatch } = this.props;
    const self = this;
    Modal.confirm({
      title: "确认删除?",
      content: `请确认是否删除？`,
      onOk() {
        dispatch({
          type: "channelNumber/delChannel",
          payload: {
            channelUserId: record.channelUserId,
          },
        }).then((res) => {
          if (res.success) {
            const { pageNum, tableData } = self.state;
            message.success("操作成功");
            if (tableData.length === 1) {
              self.setState(
                {
                  pageNum: pageNum - 1,
                },
                () => {
                  self.getTableData();
                }
              );
            } else {
              self.getTableData();
            }
          } else {
            message.error(`操作失败：${res.errMsg}`);
          }
        });
      },
      onCancel() {},
    });
  };

  renderTreeNodes = (data) =>
    (data || []).map((item) => {
      if (item.children.length > 0) {
        return (
          <TreeNode title={item.title} key={item.code} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode title={item.title} key={item.code} dataRef={item} isLeaf />
      );
    });

  onSelect = (value) => {
    this.setState(
      {
        orgCode: value[0],
        pageNum: 1,
      },
      () => {
        this.getTableData();
      }
    );
  };

  handleSearch = (values) => {
    this.setState(
      {
        name: values.name,
        policeId: values.policeId,
        pageNum: 1,
      },
      () => {
        this.getTableData();
      }
    );
  };

  hiddenOrShow = (record) => {
    const { hiddenState } = record;
    const { dispatch } = this.props;
    const self = this;
    Modal.confirm({
      title: `确认${hiddenState ? "显示" : "隐藏"}该用户吗?`,
      content: `请确认是否${hiddenState ? "显示" : "隐藏"}？`,
      onOk() {
        const payload = {
          channelUserId: record.channelUserId,
          hiddenState: hiddenState ? 0 : 1,
        };
        dispatch({ type: "channelNumber/channelHidden", payload }).then(
          (res) => {
            if (res.success) {
              message.success("操作成功");
              self.getTableData();
            } else {
              message.error(`操作失败：${res.errMsg}`);
            }
          }
        );
      },
      onCancel() {},
    });
  };

  handleTableChange = (e) => {
    const { pageSize, current } = e;
    this.setState(
      {
        pageSize,
        pageNum: current,
      },
      () => {
        this.getTableData();
      }
    );
  };

  update = () => {
    const { dispatch } = this.props;
    this.setState({
      spinLoading: true,
    });
    dispatch({ type: "channelNumber/update" }).then((res) => {
      if (res.success) {
        message.success("更新成功");
        this.setState({
          spinLoading: false,
        });
        this.getTableData();
      } else {
        message.error(`更新失败：${res.errMsg}`);
      }
    });
  };

  render() {
    const {
      visible,
      loading,
      spinLoading,
      pageNum,
      totalCount,
      tableData,
      expandedKeys,
    } = this.state;
    const { adddataSource, coldata } = this.props;
    const { userInfo } = coldata;
    const { role } = userInfo;
    const columns = [
      // {
      //   title: "账号",
      //   dataIndex: "userCode",
      //   key: "userCode",
      // },
      {
        title: "姓名",
        dataIndex: "userName",
        key: "userName",
      },
      // {
      //   title: "警号",
      //   dataIndex: "userPoliceId",
      //   key: "userPoliceId",
      // },
      {
        title: "所属机构",
        dataIndex: "orgName",
        key: "orgName",
      },
      {
        title: "性别",
        dataIndex: "userSex",
        key: "userSex",
        render: (text) => {
          if (text === 1) {
            return "男";
          }
          if (text === 2) {
            return "女";
          }
          return "未知";
        },
      },
      // {
      //   title: "岗位情况",
      //   dataIndex: "userPartType",
      //   key: "userPartType",
      //   render: (text, record) => {
      //     if (record.userPartType === 10) {
      //       return "兼职";
      //     }
      //     if (record.userPartType === 20) {
      //       return "挂职";
      //     }
      //     if (record.userPartType === 25) {
      //       return "返聘（留用）";
      //     }
      //     if (record.userPartType === 30) {
      //       return "在职";
      //     }
      //     return record.userPartType;
      //   }
      // },
      {
        title: "手机号码",
        dataIndex: "userMobile",
        key: "userMobile",
        render: (text) => text || "暂无",
      },
      {
        title: "邮箱",
        dataIndex: "officeEmail",
        key: "officeEmail",
        render: (text) => <div title={text || "暂无"}> {text || "暂无"}</div>,
      },
      {
        title: "操作",
        key: "option",
        render: (text, record) =>
          /* eslint-disable */
          (role & (1 << 0)) !== 0 ? (
            <span>
              <a
                // href="#/messageCenter/channelManager/channelNumber/edit"
                onClick={() => this.hiddenOrShow(record)}
              >
                {record.hiddenState ? "显 示" : "隐 藏"}
              </a>
              {/*
              转符庆义
              渠道号管理里面的编辑可以先隐藏吧，实际上我们不应该在通知中心提供修改其他用户信息的入口。
               <Divider type="vertical" />
              <a
                href={`#/messageCenter/channelManager/channelNumber/edit?${record.channelUserId}`}
              >
                编 辑
              </a> */}
              <Divider type="vertical" />
              <a onClick={() => this.handleDel(record)}>删 除</a>
            </span>
          ) : (
            <span>
              <a
                href={`#/messageCenter/channelManager/channelNumber/edit?${record.channelUserId}`}
              >
                编 辑
              </a>
            </span>
          ),
      },
    ];

    const { orgTree = [] } = adddataSource;
    const self = this;
    const props = {
      name: "file",
      accept: ".xls,.xlsx",
      action: "mgt/channelNo/inExcel",
      headers: {
        authorization: "authorization-text",
      },
      onChange(info) {
        // if (info.file.status !== "uploading") {
        //   // if (info.file.response.success) {
        //   // }
        //   console.log(info.file, info.fileList);
        // }
        if (info.file.status === "done") {
          if (info.file.response.success) {
            message.success(`上传成功`);
            self.closeModal();
            self.getTableData();
          } else {
            message.error(`上传失败：${info.file.response.errMsg}`);
          }
        } else if (info.file.status === "error") {
          message.error(`${info.file.name} file upload failed.`);
        }
      },
    };

    return (
      <Spin spinning={spinLoading}>
        <div className={styles.root}>
          <div className={styles.titleBox}>目标用户列表</div>
          {/* <div className={styles.top}>
            <TopSearch
              update={this.update}
              handleSearch={this.handleSearch}
              hasUpdata={(role & (1 << 0)) !== 0}
            />
          </div> */}
          <div className={styles.bottom}>
            <div className={styles.left}>
              <DirectoryTree
                expandAction={false}
                expandedKeys={expandedKeys}
                onSelect={(value) => this.onSelect(value)}
                onExpand={(newExpandedkeys) => {
                  this.setState({
                    expandedKeys: newExpandedkeys,
                  });
                }}
              >
                {this.renderTreeNodes(orgTree)}
              </DirectoryTree>
            </div>
            
            <div style={{flexShrink: 1, width: 'calc(100% - 262px)'}}>
              <div>
                <Top 
                  // visible={visible}
                  update={this.update}
                  showModal={this.showModal}
                  idaasDataSync={this.idaasDataSync}
                  hasUpdata={(role & (1 << 0)) !== 0}
                />
              </div>
              <div className={styles.right}>
                <TableList
                  columns={columns}
                  data={tableData}
                  loading={loading}
                  pageNum={pageNum}
                  totalCount={totalCount}
                  handleTableChange={this.handleTableChange}
                  rowKey="channelUserId"
                />
                {/* <AddUser visible={visible} handleAdd={this.handleAdd} /> */}
                <Modal
                  visible={visible}
                  title="导入资源"
                  onCancel={this.closeModal}
                  onOk={this.closeModal}
                  width={371}
                  destroyOnClose
                >
                  <Upload {...props} style={{ marginRight: 8 }}>
                    <Button>
                      <Icon type="upload" /> 选取文件
                    </Button>
                    <p style={{ marginTop: 8, color: "rgba(0,0,0,0.45)" }}>
                      支持拓展名：.xls或.xlsx
                    </p>
                  </Upload>
                  <div style={{ marginTop: 12 }}>
                    <a href="doc/qdhMangger.xls">下载模板</a>
                  </div>
                </Modal>
              </div>
            </div>


          </div>
        </div>
      </Spin>
    );
  }
}

export default ChannelNumber;
